﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BLL;
using Model;
using Web.Helper;

namespace Web.Areas.Manager.Controllers
{
    [UserAuthorize]
    public class QuotationController : Controller
    {
        Quotation_BLL _Quotation_BLL = new Quotation_BLL();
        Customer_BLL _Customer_BLL = new Customer_BLL();
        CustomerContact_BLL _CustomerContact_BLL = new CustomerContact_BLL();
        Sys_Users_BLL _Sys_Users_BLL = new Sys_Users_BLL();
        SalesOpportunity_BLL _SalesOpportunity_BLL = new SalesOpportunity_BLL();
        M_QuotationProduct_BLL _M_QuotationProduct_BLL = new M_QuotationProduct_BLL();
        SendBill_BLL _SendBill_BLL = new SendBill_BLL();
        SellBack_BLL _SellBack_BLL = new SellBack_BLL();
        ContactOrder_BLL _ContactOrder_BLL = new ContactOrder_BLL();
        private M_ReceiveForm_BLL _M_ReceiveForm_BLL = new M_ReceiveForm_BLL();
       // ReceiveForm_BLL _ReceiveForm_BLL = new ReceiveForm_BLL();

        public virtual ActionResult Index(int? pageIndex, string keyword)
        {
            var model = _Quotation_BLL.Get();
            if (!string.IsNullOrEmpty(keyword))
            {
                //  model = model.Where(a => a.UserName.Contains(keyword));
            }
            return View(model.ToPagedList(pageIndex));
        }


        public virtual ActionResult Details(Guid Id, bool toxls=false)
        {
            ViewBag.toxls = toxls;

            if (toxls)
            {
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                Response.ContentType = "application/vnd.ms-excel";
                Response.AppendHeader("Content-Disposition", "inline;filename=" + DateTime.Now + ".xls");
            }
            var item = _Quotation_BLL.Get(Id);
            return View(item);
        }


        public virtual ActionResult Edit(Guid? Id, string strCompanyId)
        {
            if (_SalesOpportunity_BLL.Get().Count() == 0)
            {
                Response.Write("<script>alert('请先添加销售管理中的销售机会信息')</script>");
                Response.End();
            }
            
            
           
            var customer = _Customer_BLL.Get();
            var customercontact = _CustomerContact_BLL.Get();
            var customerId = customer.FirstOrDefault().Id;
            var customerIdcontactId = customercontact.FirstOrDefault().Id;
            if (!string.IsNullOrEmpty(strCompanyId))
            {
                customerId = new Guid(strCompanyId);
                SelectList listItem = new SelectList(customer.AsEnumerable(), "Id", "CustomerName", customerId);
                ViewData.Add("Customer", listItem);
            }
            else
            {
                SelectList listItem = new SelectList(customer.AsEnumerable(), "Id", "CustomerName");
                ViewData.Add("Customer", listItem);
            }
            customercontact = customercontact.Where(a => a.CustomerId == customerId);

            SelectList listItem2 = new SelectList(customercontact.AsEnumerable(), "Id", "Name");
            ViewData.Add("CustomerContact", listItem2);

            ViewData["Sys_Users"] = _Sys_Users_BLL.Get();
            ViewData["SalesOpportunity"] = _SalesOpportunity_BLL.Get();
            IList<M_QuotationProduct> list = new List<M_QuotationProduct>();
            ViewData["productss"] = list;

            var item = _Quotation_BLL.Get(Id);

            if (Id == null)
            {
                ViewData["Id"] = null;

            }
            else
            {
                ViewData["Id"] = Id;

            }

            return View(item);
        }

        [HttpPost]
        public virtual ActionResult Edit(Guid? Id, Quotation collection)
        {
            IList<M_QuotationProduct> list = new List<M_QuotationProduct>();

            string[] ProductNumber = Request["ProductNumber"].Split(',');

            string[] productName = Request["productName"].Split(',');
            string[] Quantity = Request["Quantity"].Split(',');
            string[] Price = Request["Price"].Split(',');
            string[] Discount = Request["Discount"].Split(',');
            var money = 0M;
            
            for (int i = 0; i < ProductNumber.Length; i++)
            {
                M_QuotationProduct item1 = new M_QuotationProduct();

                item1.Id = Guid.NewGuid();
                item1.ItemId = Guid.NewGuid();
                item1.ProductNumber = string.IsNullOrEmpty(ProductNumber[i]) ? "" : ProductNumber[i];
                item1.productName = string.IsNullOrEmpty(productName[i]) ? "" : productName[i];
                item1.Quantity = int.Parse(String.IsNullOrEmpty(Quantity[i]) || !StringExt.IsUint(Quantity[i]) ? "0" : Quantity[i]);
                item1.Price = decimal.Parse(String.IsNullOrEmpty(Price[i])||!StringExt.IsPrice(Price[i]) ? "0" : Price[i]);

                item1.Discount = int.Parse(String.IsNullOrEmpty(Discount[i]) ? "0" : Discount[i]);
               
                item1.Subtotal = item1.Price * item1.Quantity * item1.Discount / 100;
                item1.Datetime = DateTime.Now;
                item1.UserId = new Guid(User.Identity.Name);
                money = money +item1.Subtotal;
                list.Add(item1);

                if (string.IsNullOrEmpty(ProductNumber[i]))
                {
                    ModelState.AddModelError("ProductNumber", "请填写商品编号");
                }
                if (string.IsNullOrEmpty(productName[i]))
                {
                    ModelState.AddModelError("productName", "请填写商品名称");
                }
            
                if (string.IsNullOrEmpty(Price[i]) ||!StringExt.IsPrice(Price[i]))
                {
                    ModelState.AddModelError("Price", "商品价格填写不正确");
                }
                if (string.IsNullOrEmpty(Quantity[i]) || !StringExt.IsUint(Quantity[i]))
                {
                    ModelState.AddModelError("Quantity", "商品数量填写不正确");
                }
                if (string.IsNullOrEmpty(Discount[i]))
                {
                    ModelState.AddModelError("Discount", "请填写商品折扣");
                }

            }

            ViewData["productss"] = list;

            if (!ModelState.IsValid)
            {
                var customer = _Customer_BLL.Get();
                var customercontact = _CustomerContact_BLL.Get();
                var customerId = customer.FirstOrDefault().Id;
                var customerIdcontactId = customercontact.FirstOrDefault().Id;

                customerId = collection.CustomerId;
                    SelectList listItem = new SelectList(customer.AsEnumerable(), "Id", "CustomerName", customerId);
                    ViewData.Add("Customer", listItem);
               
                customercontact = customercontact.Where(a => a.CustomerId == customerId);

                SelectList listItem2 = new SelectList(customercontact.AsEnumerable(), "Id", "Name");
                ViewData.Add("CustomerContact", listItem2);

                ViewData["Sys_Users"] = _Sys_Users_BLL.Get();
                ViewData["SalesOpportunity"] = _SalesOpportunity_BLL.Get();
                return View(collection);
            }

            collection.Totale =money - (money * collection.Taxrate) / 100;
            _Quotation_BLL.Save(Id, ref collection);

            IQueryable<M_QuotationProduct> lists = collection.M_QuotationProduct.AsQueryable();
            if (lists.Count() > 0)
            {
                foreach (var item in lists)
                {
                    _M_QuotationProduct_BLL.Delete(item.Id);
                }
            }


            for (int i = 0; i < ProductNumber.Length; i++)
            {
                M_QuotationProduct item1 = new M_QuotationProduct()
                {
                    Id = Guid.NewGuid(),
                    ItemId = collection.Id,
                    ProductNumber = ProductNumber[i],
                    productName = productName[i],
                    Quantity = int.Parse(Quantity[i]),
                    Price = decimal.Parse(Price[i]),

                    Discount = int.Parse(Discount[i]),
                    Subtotal= decimal.Parse(Price[i]) * int.Parse(Quantity[i]) * int.Parse(Discount[i]) / 100,
                    Datetime = DateTime.Now,
                    UserId = new Guid(User.Identity.Name)

                };
                _M_QuotationProduct_BLL.Save(null, ref item1);

            }
            return RedirectToAction("Index", MyrouteValues.Get());
        }

        [HttpDelete]
        public virtual ActionResult Delete(Guid Id)
        {
            //var model = _Quotation_BLL.Get(Id);
            
            //foreach (var item in model.ContactOrders)
            //{
            //    //foreach (var item3 in item.M_ReceiveForm)
            //    //{
            //    //    _M_ReceiveForm_BLL.Delete(item3.Id);
            //    //}
            //    foreach (var item1 in item.SellBacks)
            //    {
            //        _SellBack_BLL.Delete(item1.Id);
            //    }
            //    foreach (var item2 in item.SendBills)
            //    {
            //        _SendBill_BLL.Delete(item2.Id);
            //    }
            //    _ContactOrder_BLL.Delete(item.Id);
            //   }
           
            _Quotation_BLL.Delete(Id);

            return RedirectToAction("Index", MyrouteValues.Get());
        }
    }
}
